package com.cn.netty.customize.client;

import com.cn.netty.basic.EchoClientHandler;
import com.cn.netty.basic.EchoServer;
import com.cn.netty.customize.handler.DecodeHandler;
import com.cn.netty.customize.handler.EncodeHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class Client {

  public static void main(String[] args) {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress("127.0.0.1", 9999))
            .handler(new ChannelInitializer<SocketChannel>() {//这里是个handler
              @Override
              protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));

                ch.pipeline().addLast(new CheckAndWriteHandler(5)); //读空闲 就触发心跳

                ch.pipeline().addLast(
                        new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 2,
                                0, 2)); //入站  粘包拆包解码
                ch.pipeline().addLast(new LengthFieldPrepender(2));//出站  "粘包拆包"编码

                ch.pipeline().addLast(new EncodeHandler()); //出站 编码
                ch.pipeline().addLast(new DecodeHandler()); //入站 解码

                ch.pipeline().addLast(new ReadTimeoutHandler(5));//10秒 没有可读消息就报错，报错信息往下传递


                ch.pipeline().addLast(new ReadTimeoutHandler(10));//读空闲 就触发读取超时异常

                ch.pipeline().addLast(new HearBeatReqHandler());

//                ch.pipeline().addLast(new WriteTimeoutHandler(11));

                ch.pipeline().addLast(new ClientHandler());
              }
            });

    try {

      ChannelFuture sync = bootstrap.connect().sync();
      sync.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}
